import { buildUUID } from '#/utils/uuid'

import COS from 'cos-js-sdk-v5'
import { requestClient } from '../request'
import type { COSCredentialRespone } from './model/cos'

export const env = import.meta.env.VITE_NODE_ENV === 'production' ? 'prod' : 'dev'

// 角色管理
export default class UploadApi {
    static get inst() {
        return UploadApi._inst || (UploadApi._inst = new UploadApi())
    }
    private static _inst: UploadApi
    static joinPath(...args: string[]) {
        const arr = args.filter(Boolean)
        const len = arr.length
        if (len === 1) return args[0]
        // 去掉每个参数的末尾斜杠和开头斜杠
        const cleanedArgs = arr.map((str, index) => {
            // 第一个只去掉尾部
            if (index === 0) {
                return str.replace(/\/$/, '')
            }
            // 最后一个只去掉前面
            if (len - 1 === index) {
                return str.replace(/^\//, '')
            }
            return str.replace(/\/$/, '').replace(/^\//, '')
        })

        // 连接所有字符串，确保只有一个斜杠
        const result = cleanedArgs.join('/')

        return result
    }

    async fileUpload(opts: {
        data?: Record<string, any>
        file: File
        filename?: string
        name?: string
        onProgress?: (params: {
            /** 已上传/下载的字节数，单位 B（字节）  */
            loaded: number
            /** 进度百分比，范围是 0-1，保留两位小数  */
            percent: number
            /** 速度，单位 B/s  */
            speed: number
            /** 要上传/下载的文件的大小，单位 B（字节）  */
            total: number
        }) => any
    }) {
        const { file, onProgress } = opts

        // 是否使用cos TODO:需要替换成cos方式
        const isCOS = false
        // const fileExtension = getFileExtension(file.name)

        if (!isCOS) {
            return new Promise((resolve) => {
                this.uploadByApi({
                    file
                }).then((fileName) => {
                    resolve({
                        data: {
                            url: fileName
                        }
                    })
                })
            })
        }

        let Bucket = ''
        let Region = ''
        let CdnUrl = ''
        const suffix = this.getFileExtension(file.name)
        const result = await this.getImageUploadCredential()

        Bucket = result.bucketName
        Region = result.region
        CdnUrl = result.host
        return new Promise((resolve, reject) => {
            // const formData = new FormData()
            // formData.append('type', 'IMAGE')
            const fileName =
                UploadApi.joinPath(result.folderPath, `/${env}/images/${buildUUID()}${suffix}`) ||
                ''

            const cos = new COS({
                // 必选参数
                getAuthorization(_options, callback) {
                    const data = result
                    const credentials = data && data.credentials
                    if (!data || !credentials) return console.error('credentials invalid')
                    if (callback) {
                        const parameter = {
                            TmpSecretId: credentials.tmpSecretId,
                            TmpSecretKey: credentials.tmpSecretKey,
                            XCosSecurityToken: credentials.sessionToken,
                            StartTime: data.startTime,
                            ExpiredTime: data.expiredTime,
                            ScopeLimit: true
                        } as COS.GetAuthorizationCallbackParams
                        callback(parameter)
                    }
                }
            })

            cos.putObject(
                {
                    Bucket,
                    Region,
                    Key: fileName,
                    StorageClass: 'STANDARD',
                    Body: file,
                    onProgress
                },
                (err, data) => {
                    if (data && data.statusCode === 200) {
                        resolve({
                            data: {
                                url: CdnUrl + fileName
                            }
                        })
                    } else {
                        reject(err)
                    }
                }
            )
        })
    }

    getFileExtension(name: string) {
        return name.slice(name.lastIndexOf('.')).toLowerCase()
    }

    /**
     * 获取cos上传凭证
     */
    getImageUploadCredential() {
        return requestClient.get<COSCredentialRespone>('/tx/cos/api/getUploadCredential')
    }

    async uploadByApi(params: { file: any }) {
        return requestClient.post<string>('/aws/api/imgUpload', params, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    }
}
